package com.aliyun.messagemgt.common.validation;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @ClassName: EnumValid
 * @Description: 校验枚举值有效性
 * @Author: wugongzi
 * @Date: 2021/9/29 11:34
 * @Version: 1.0
 */
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValid.Validator.class)
public @interface EnumValid {
    String message() default "{custom.value.invalid}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 目标枚举类
     */
    Class<?> target() default Class.class;

    /**
     * 是否忽略空值
     */
    boolean ignoreEmpty() default true;


    class Validator implements ConstraintValidator<EnumValid, Object> {

        // 枚举校验注解
        private EnumValid annotation;

        @Override
        public void initialize(EnumValid constraintAnnotation) {

            annotation = constraintAnnotation;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            boolean result = false;

            Class<?> cls = annotation.target();
            boolean ignoreEmpty = annotation.ignoreEmpty();

            // target为枚举，并且value有值，或者不忽视空值，才进行校验
            if (cls.isEnum() && (value != null || !ignoreEmpty)) {

                Object[] objects = cls.getEnumConstants();
                for (Object obj : objects) {
                    // 使用此注解的枚举类需要重写toString方法，改为需要验证的值
                    if (obj.toString().equals(String.valueOf(value))) {
                        result = true;
                        break;
                    }
                }
            } else {
                result = true;
            }
            return result;
        }

    }
}
